Qn CGI Web-Based Registration and Database Application

Develop a student registration web application using Python CGI and SQLite/MySQL.

Perform the following operations:

1. Create an HTML registration form that accepts student details such as Name, Roll Number, Age, Course and Email.
2. Use Python CGI to receive and process the form data.
3. Use the `cgi` module and `FieldStorage()` to retrieve user inputs.
4. Display the submitted student details on a separate web page.
5. Establish a connection with an SQLite/MySQL database.
6. Create a Student table with appropriate fields and constraints.
7. Insert the submitted student details into the database.
8. Display all registered student records on a web page.
9. Implement UPDATE and DELETE operations using the CGI interface.
10. Display appropriate success or error messages after each operation.

Your question requires:
- An HTML registration form displayed in a browser.
- A web server to receive form submissions.
- Python CGI to process the submitted data.
- SQLite/MySQL database operations.
- Separate web pages to display, update and delete student records.

Important: The cgi module was deprecated and removed from Python 3.13 onwards. Since your computer has Python 3.14, use Python 3.12 for this particular practical if your syllabus specifically requires cgi.FieldStorage().

Step 1

2. Open XAMPP Control Panel.
3. Find Apache.
4. Click Start.
5. Open your browser and visit:
http://localhost/

If the XAMPP dashboard appears, Apache is working.

Step 2 – Install Python 3.12
Install Python 3.12 alongside your existing Python version. You do not need to uninstall Python 3.14.

Open Command Prompt and check:
py -3.12 --version

Expected output:
Python 3.12.x

Check whether CGI is available:
py -3.12 -c "import cgi; print('CGI module available')"

You should see:
CGI module available


Python's official documentation confirms that Python 3.12 was the last version to include the standard-library cgi module. 

Python 3.13.15 documentation+1

Step 3 – Configure Apache for CGI
1. Open XAMPP Control Panel.
2. Click Config next to Apache.
3. Open httpd.conf.
4. Find the CGI configuration section.
5. Check that the following configuration exists. If necessary, add or modify it.
ScriptAlias /cgi-bin/ "C:/xampp/cgi-bin/"

<Directory "C:/xampp/cgi-bin">
    AllowOverride None
    Options +ExecCGI
    AddHandler cgi-script .cgi .py
    Require all granted
</Directory>

ScriptInterpreterSource Script

Save the file.

6. Stop Apache and start it again.

Important: If Apache fails to start, check for duplicate or conflicting CGI configuration before continuing.
3. Create the Project
Open File Explorer and navigate to:
C:\xampp\


Inside XAMPP, you will use two folders:
- htdocs – stores your HTML registration page.
- cgi-bin – stores your Python CGI program.
Create this structure:
C:\xampp\
│
├── htdocs\
│   └── cgi_student_app\
│       └── index.html
│
└── cgi-bin\
    └── students.py


The SQLite database will be created automatically by the Python program.
4. Create the HTML Registration Form
Open VS Code or Notepad.

Create:

C:\xampp\htdocs\cgi_student_app\index.html

Paste this code:
<!DOCTYPE html>
<html>
<head>
    <title>Student Registration</title>
</head>
<body>

    <h2>Student Registration Form</h2>

    <form action="/cgi-bin/students.py" method="POST">

        <input type="hidden" name="action" value="register">

        Name:
        <input type="text" name="name" required>
        <br><br>

        Roll Number:
        <input type="text" name="roll" required>
        <br><br>

        Age:
        <input type="number" name="age" required>
        <br><br>

        Course:
        <input type="text" name="course" required>
        <br><br>

        Email:
        <input type="email" name="email" required>
        <br><br>

        <input type="submit" value="Register">

    </form>

    <br>

    <a href="/cgi-bin/students.py?action=list">
        View All Students
    </a>

</body>
</html>


Explanation:
- <form> creates the registration form.
- action specifies which Python CGI program receives the data.
- method="POST" sends the form data to Python.
- name attributes identify the submitted values.
- The hidden action field tells Python that this is a registration request.
5. Create the Python CGI Program
Create:

C:\xampp\cgi-bin\students.py

Before writing the program, find your Python 3.12 executable path:
py -3.12 -c "import sys; print(sys.executable)"


For example, it might display:
C:\Users\YourName\AppData\Local\Programs\Python\Python312\python.exe


Copy that path. Replace the example path in the first line of the following program with your actual path. Use forward slashes.
Complete Python CGI code
#!C:/Users/YourName/AppData/Local/Programs/Python/Python312/python.exe    try:        student_id = int(form.getfirst("id", "0"))        name = form.getfirst("name", "").strip()        roll = form.getfirst("roll", "").strip()        age = int(form.getfirst("age", "0"))        course = form.getfirst("course", "").strip()        email = form.getfirst("email", "").strip()        if not name or not roll or age <= 0 or not course or not email:            raise ValueError("Enter valid student details.")        cur.execute("""        UPDATE Student        SET name=?, roll=?, age=?, course=?, email=?        WHERE id=?        """, (name, roll, age, course, email, student_id))        con.commit()        if cur.rowcount == 0:            page("Error", "<p>Student not found.</p>")        else:            page("Update Successful", "<p>Student updated successfully!</p>")    except (ValueError, sqlite3.IntegrityError) as e:        page("Update Error", "<p>" + html.escape(str(e)) + "</p>")# Delete studentelif action == "delete":    try:        student_id = int(form.getfirst("id", "0"))        cur.execute(            "DELETE FROM Student WHERE id=?",            (student_id,)        )        con.commit()        if cur.rowcount == 0:            page("Error", "<p>Student not found.</p>")        else:            page("Delete Successful", "<p>Student deleted successfully!</p>")    except ValueError:        page("Error", "<p>Invalid student ID.</p>")# Invalid actionelse:    page("Error", "<p>Invalid operation.</p>")con.close()



What this single Python program handles:
Operation	CGI action
Registration	register
Display all records	list
Display edit form	edit
Update student	update
Delete student	delete

cgi.FieldStorage() receives the form data, and SQLite performs the database operations. Parameterized SQL queries (?) help prevent SQL injection.
6. Run the Application
Step 1 – Start Apache
Open XAMPP Control Panel and make sure Apache is running.
Step 2 – Open the Registration Form
Open your browser and visit:
http://localhost/cgi_student_app/index.html


You should see the student registration form.







medium.com


Step 3 – Register a Student
Enter sample details:
Field	Sample value
Name	Arun
Roll Number	MCA001
Age	22
Course	MCA
Email	arun@gmail.com

Click Register.

The Python CGI program will:
1. Receive the submitted form data.
2. Read the values using cgi.FieldStorage().
3. Connect to SQLite.
4. Insert the student details.
5. Display a registration success message and submitted details.
Step 4 – Display All Student Records
Click View All Students.

Or open:
http://localhost/cgi-bin/students.py?action=list


You should see all registered students in a table, with Edit and Delete options.
Step 5 – Update a Student
1. Click Edit beside a student.
2. Change the required details.
3. Click Update Student.
4. The database will be updated.
Step 6 – Delete a Student
1. Click Delete beside a student.
2. The selected student will be deleted.
3. A success message will be displayed.
7. Database Location
I recommend keeping your database outside the public website folder.

Change this line in students.py:
"C:/xampp/htdocs/cgi_student_app/students.db"

To:
"C:/xampp/students.db"

SQLite will automatically create the database file when the program first runs, provided Apache has permission to write there.



